'use strict';
const {
	verifyToken
} = require("wx-common")

exports.main = async (event, context) => {
	const db = uniCloud.database()
	const dbcmd = db.command
	const payload = event.token ? await verifyToken(event.token) : null

	console.log("event,", event, )

	if (payload && payload.openid) {
		// openid
		const openid = payload.openid

		if (event.id) {
			// 编辑
			let params = {
				owner: openid,
				name: event.name,
				address: event.address,
				geoPoint: new db.Geo.Point(event.longitude, event.latitude),
				totalBook: 0,
			}

			let res = db.collection("bookShelf").where({
				id: dbcmd.eq(event.id)
			}).update(params)

			//返回数据给客户端
			return {
				code: 200,
				message: "修改成功"
			}
		} else {
			// 新增
			let params = {
				owner: openid,
				name: event.name,
				address: event.address,
				geoPoint: new db.Geo.Point(event.longitude, event.latitude),
				totalBook: 0,
				id: `bs${+ new Date()}`
			}

			let res = db.collection("bookShelf").add(params)

			//返回数据给客户端
			return {
				code: 200,
				message: "新建成功"
			}
		}
	} else {
		return payload
	}
};
